package com.dq.rbac.commons.security;

import cn.hutool.json.JSONUtil;
import com.dq.rbac.vo.R;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @project: rbac
 * @ClassName: jwt自定义认证失败处理
 * @author: dq
 * @creat: 2022/12/27 11:00
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //jwt Error错误返回
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        byte[] result = JSONUtil.toJsonStr(R.error().code(HttpServletResponse.SC_UNAUTHORIZED).message("认证失败")).getBytes(StandardCharsets.UTF_8);
        outputStream.write(result);
        outputStream.flush();
        outputStream.close();
    }
}
